/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-12
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-04-16
 * @Description: 
 */
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http_parser/http_parser.dart'; // 解析 MediaType
import 'mobile_image_picke.dart' if (dart.library.html) 'web_image_picke.dart';

abstract class ImagePickerHelper {
  /// 统一入口：选择并处理图片
  static Future<XFile?> pickAndProcessImage(
      {bool enableFreeStyle = false}) async {
    return processImage(enableFreeStyle);
  }

  // 上传完成后，文件内存释放
  static Future<void> releaseImage(XFile? file) async {
    try {
      cleanTempFiles(file);
      return;
    } catch (e) {
      debugPrint('释放文件失败: $e');
      throw Exception('释放文件失败: $e');
    }
  }

  // 处理图片文件上传时
  static Future<MultipartFile?> convertXFileToMultipart(XFile file) async {
    final mimeType = lookupMimeType(file.name) ?? 'application/octet-stream';
    if (kIsWeb) {
      // Web 端需要读取字节数据
      final bytes = await file.readAsBytes();
      return MultipartFile.fromBytes(bytes,
          filename: file.name, contentType: MediaType.parse(mimeType));
    } else {
      // 移动端直接使用本地文件路径
      return MultipartFile.fromFile(file.path,
          filename: file.name, contentType: MediaType.parse(mimeType));
    }
  }

  // 仅支持的图片格式
  static final Map<String, String> _imageMimeTypes = {
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpg',
    'png': 'image/png',
    'webp': 'image/webp',
  };

  // 获取文件的 MIME 类型
  static lookupMimeType(String filename) {
    final extension = filename.split('.').last.toLowerCase();
    return _imageMimeTypes[extension];
  }
}
